<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/11/11
 * Time: 10:13
 */

namespace business\bigdata\services\queues;

use business\base\caches\DataCache;
use business\bigdata\repositories\MaterialRepository;
use common\queue\QueueConstants;
use common\utils\DateTimeUtils;

class MaterialProducerService extends BaseService
{
    /**
     * 增量方式更新时: 记录最近一次材料索引查询的时间的key
     */
    const LATEST_MATERIAL_QUERY_TIME_KEY = 'Last-Bigdata-Material-Query-Time';

    /**
     * 指定模块
     */
    const MODULE = 'material';

    /**
     * 全量更新供应商索引
     * @return mixed|void
     */
    public function full()
    {
        /** @var iQueue $queue */
        $queue = \yii::$app->iQueue->createClient(
            QueueConstants::BIG_DATA_MATERIAL_INDEX_QUEUE
        );

        $materialRepository = new MaterialRepository();
        $dataCache          = new DataCache();

        $totalCount = $materialRepository->getMaterialCount();
        $loopCount = ceil($totalCount / self::MAX_COUNT_PER_QUERY);

        for ($i = 0; $i < $loopCount; $i++) {
            $materialNames = $materialRepository->getAllMaterialName(($i * self::MAX_COUNT_PER_QUERY),
                self::MAX_COUNT_PER_QUERY);

            $materialCount = count($materialNames);

            $values   = implode(self::DELIMITER, $materialNames);

            $source   = ['source' => 'material', 'values' => $values];
            $data     = array_merge($source, ['uuid' => $this->uuid(), 'created_on' => DateTimeUtils::now()]);

            $cacheKey = $message = md5(serialize($source));

            $queueCacheName = self::MODULE . '-' . QueueConstants::QUEUE_CHACHE_NAME;

            // 如果缓存数据存在则先删除原数据
            $this->existInCache($queueCacheName, $cacheKey)
                && $dataCache->delRecordByHash($queueCacheName, $cacheKey);

            $dataCache->saveRecordByHash($queueCacheName, $cacheKey, $data);

            $queue->sendMsg($message, function ($msgBody) use($loopCount, $i, $materialCount) {
                echo '大数据材料-已插入队列比例: ' . ($i + 1) . '/' . $materialCount . '/' . $loopCount . PHP_EOL;
            });

            usleep(self::MICRO_SECOND);
        }
    }

    /**
     * 重发机制
     */
    public function resend()
    {
        $this->processResend(
            QueueConstants::BIG_DATA_MATERIAL_INDEX_QUEUE
            , self::MODULE
            , '大数据材料'
        );
    }

    /**
     * 清除已经消费过的队列数据
     * @throws \yii\base\InvalidConfigException
     */
    public function clearConsumerQueue()
    {
        $this->processclearConsumerQueue(self::MODULE);
    }
}
